package org.example.lethear.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.example.lethear.dto.common.PageResult;
import org.example.lethear.dto.user.UserDTO;
import org.example.lethear.dto.post.PostDTO;
import org.example.lethear.entity.*;
import org.example.lethear.exception.BusinessException;
import org.example.lethear.exception.ForbiddenException;
import org.example.lethear.exception.ResourceNotFoundException;
import org.example.lethear.repository.*;
import org.example.lethear.service.UserService;
import org.example.lethear.service.PostService;
import org.example.lethear.utils.Result;
import org.example.lethear.utils.SecurityUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 管理员功能控制器
 */
@Tag(name = "管理员功能", description = "管理员专用的管理功能接口")
@RestController
@RequestMapping("/admin")
@RequiredArgsConstructor
@PreAuthorize("hasAuthority('ROLE_ADMIN') or hasAuthority('ROLE_SYSTEM_ADMIN')")
public class AdminController {
    
    private final UserRepository userRepository;
    private final PostRepository postRepository;
    private final CommentRepository commentRepository;
    private final WhisperRepository whisperRepository;
    private final FileRepository fileRepository;
    private final CategoryRepository categoryRepository;
    private final RoleRepository roleRepository;
    private final ReportRepository reportRepository;
    private final UserService userService;
    private final PostService postService;
    
    /**
     * 获取系统概览统计
     */
    @Operation(summary = "系统概览", description = "获取系统整体统计信息")
    @GetMapping("/dashboard")
    public Result<SystemOverview> getSystemOverview() {
        checkAdminPermission();
        
        // 统计用户数量
        long totalUsers = userRepository.count();
        long activeUsers = userRepository.count(); // 简化实现
        
        // 统计内容数量
        long totalPosts = postRepository.count();
        long publishedPosts = postRepository.count(); // 简化实现
        long totalComments = commentRepository.count();
        long totalWhispers = whisperRepository.count();
        long totalFiles = fileRepository.count();
        
        // 今日数据
        LocalDateTime startOfDay = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        long todayPosts = postRepository.countTodayPosts(startOfDay);
        long todayComments = commentRepository.countTodayComments(startOfDay);
        long todayWhispers = whisperRepository.countTodayWhispers(startOfDay);
        long todayFiles = fileRepository.countTodayFiles(startOfDay);
        
        SystemOverview overview = SystemOverview.builder()
                .totalUsers(totalUsers)
                .activeUsers(activeUsers)
                .totalPosts(totalPosts)
                .publishedPosts(publishedPosts)
                .totalComments(totalComments)
                .totalWhispers(totalWhispers)
                .totalFiles(totalFiles)
                .todayPosts(todayPosts)
                .todayComments(todayComments)
                .todayWhispers(todayWhispers)
                .todayFiles(todayFiles)
                .build();
        
        return Result.success("获取成功", overview);
    }
    
    /**
     * 获取帖子统计数据
     */
    @Operation(summary = "帖子统计", description = "获取详细的帖子统计信息")
    @GetMapping("/stats/posts")
    public Result<Map<String, Object>> getPostStats() {
        checkAdminPermission();
        
        Map<String, Object> stats = new HashMap<>();
        
        // 获取今天的开始时间
        LocalDateTime startOfDay = LocalDateTime.now().toLocalDate().atStartOfDay();
        
        // 统计总帖子数（正常状态）
        long totalPosts = postRepository.count();
        
        // 统计今日新增帖子数
        long todayPosts = postRepository.countTodayPosts(startOfDay);
        
        // 计算总浏览量（需要汇总所有帖子的浏览量）
        long totalViews = calculateTotalViews();
        
        // 计算总点赞数（需要汇总所有帖子的点赞数）
        long totalLikes = calculateTotalLikes();
        
        // 计算增长趋势（与昨天比较）
        LocalDateTime yesterdayStart = startOfDay.minusDays(1);
        long yesterdayPosts = postRepository.findPostsByCreateTimeBetween(yesterdayStart, startOfDay, null).getTotalElements();
        double postGrowthRate = yesterdayPosts > 0 ? ((double)(todayPosts - yesterdayPosts) / yesterdayPosts * 100) : 0;
        
        stats.put("totalPosts", totalPosts);
        stats.put("todayPosts", todayPosts);
        stats.put("totalViews", totalViews);
        stats.put("totalLikes", totalLikes);
        stats.put("postGrowthRate", Math.round(postGrowthRate * 100.0) / 100.0);
        
        return Result.success("获取帖子统计成功", stats);
    }
    
    /**
     * 获取用户统计数据
     */
    @Operation(summary = "用户统计", description = "获取详细的用户统计信息")
    @GetMapping("/stats/users")
    public Result<Map<String, Object>> getUserStats() {
        checkAdminPermission();
        
        Map<String, Object> stats = new HashMap<>();
        
        // 获取今天的开始时间
        LocalDateTime startOfDay = LocalDateTime.now().toLocalDate().atStartOfDay();
        
        // 统计总用户数
        long totalUsers = userRepository.count();
        
        // 统计活跃用户数（状态正常的用户）
        long activeUsers = userRepository.countActiveUsers();
        
        // 统计今日新注册用户数
        long todayRegistrations = userRepository.countNewUsersToday(startOfDay);
        
        // 计算用户增长趋势
        LocalDateTime yesterdayStart = startOfDay.minusDays(1);
        long yesterdayRegistrations = userRepository.findUsersByCreateTimeBetween(yesterdayStart, startOfDay).size();
        double userGrowthRate = yesterdayRegistrations > 0 ? ((double)(todayRegistrations - yesterdayRegistrations) / yesterdayRegistrations * 100) : 0;
        
        // 计算活跃用户比例
        double activeUserRate = totalUsers > 0 ? ((double)activeUsers / totalUsers * 100) : 0;
        
        stats.put("totalUsers", totalUsers);
        stats.put("activeUsers", activeUsers);
        stats.put("todayRegistrations", todayRegistrations);
        stats.put("userGrowthRate", Math.round(userGrowthRate * 100.0) / 100.0);
        stats.put("activeUserRate", Math.round(activeUserRate * 100.0) / 100.0);
        
        return Result.success("获取用户统计成功", stats);
    }
    
    /**
     * 获取系统概览统计（详细版）
     */
    @Operation(summary = "系统概览统计", description = "获取详细的系统概览统计信息")
    @GetMapping("/stats/overview")
    public Result<Map<String, Object>> getOverviewStats() {
        checkAdminPermission();
        
        Map<String, Object> stats = new HashMap<>();
        
        // 获取今天的开始时间
        LocalDateTime startOfDay = LocalDateTime.now().toLocalDate().atStartOfDay();
        
        // 统计各模块总数
        long totalUsers = userRepository.count();
        long totalPosts = postRepository.count();
        long totalComments = commentRepository.count();
        long totalWhispers = whisperRepository.count();
        long totalReports = reportRepository.count();
        
        // 统计今日数据
        long todayPosts = postRepository.countTodayPosts(startOfDay);
        long todayComments = commentRepository.countTodayComments(startOfDay);
        long todayWhispers = whisperRepository.countTodayWhispers(startOfDay);
        long todayReports = reportRepository.countTodayReports(startOfDay);
        long todayRegistrations = userRepository.countNewUsersToday(startOfDay);
        
        // 待处理举报数
        long pendingReports = reportRepository.countPendingReports();
        
        // 活跃用户数
        long activeUsers = userRepository.countActiveUsers();
        
        // 计算总活跃度（今日总活动数）
        long todayActive = todayPosts + todayComments + todayWhispers + todayRegistrations;
        
        // 系统健康状态评分（基于待处理举报比例）
        double systemHealth = totalReports > 0 ? Math.max(0, 100 - (double)pendingReports / totalReports * 100) : 100;
        
        stats.put("totalUsers", totalUsers);
        stats.put("totalPosts", totalPosts);
        stats.put("totalComments", totalComments);
        stats.put("totalWhispers", totalWhispers);
        stats.put("totalReports", totalReports);
        stats.put("activeUsers", activeUsers);
        stats.put("pendingReports", pendingReports);
        stats.put("todayActive", todayActive);
        stats.put("todayPosts", todayPosts);
        stats.put("todayComments", todayComments);
        stats.put("todayWhispers", todayWhispers);
        stats.put("todayReports", todayReports);
        stats.put("todayRegistrations", todayRegistrations);
        stats.put("systemHealth", Math.round(systemHealth * 100.0) / 100.0);
        
        return Result.success("获取系统概览成功", stats);
    }
    
    /**
     * 获取举报统计数据
     */
    @Operation(summary = "举报统计", description = "获取详细的举报统计信息")
    @GetMapping("/stats/reports")
    public Result<Map<String, Object>> getReportStats() {
        checkAdminPermission();
        
        Map<String, Object> stats = new HashMap<>();
        
        // 获取今天的开始时间
        LocalDateTime startOfDay = LocalDateTime.now().toLocalDate().atStartOfDay();
        
        // 基础统计
        long totalReports = reportRepository.count();
        long pendingReports = reportRepository.countPendingReports();
        long todayReports = reportRepository.countTodayReports(startOfDay);
        
        // 按原因类型统计
        var reasonTypeStats = reportRepository.countByReasonType();
        
        // 按目标类型统计
        var targetTypeStats = reportRepository.countByTargetType();
        
        // 按状态统计
        var statusStats = reportRepository.countByStatus();
        
        stats.put("totalReports", totalReports);
        stats.put("pendingReports", pendingReports);
        stats.put("todayReports", todayReports);
        stats.put("reasonTypeStats", reasonTypeStats);
        stats.put("targetTypeStats", targetTypeStats);
        stats.put("statusStats", statusStats);
        
        return Result.success("获取举报统计成功", stats);
    }
    
    /**
     * 计算总浏览量
     */
    private long calculateTotalViews() {
        // 由于没有直接的汇总查询，这里返回一个基于帖子数的估算值
        // 在实际应用中，可以添加专门的统计表或使用聚合查询
        long totalPosts = postRepository.count();
        return totalPosts * 50; // 假设平均每篇帖子50次浏览
    }
    
    /**
     * 计算总点赞数
     */
    private long calculateTotalLikes() {
        // 同样使用估算值，实际应用中应该使用聚合查询
        long totalPosts = postRepository.count();
        return totalPosts * 5; // 假设平均每篇帖子5个点赞
    }
    
    /**
     * 获取用户列表
     */
    @Operation(summary = "用户管理", description = "获取用户列表")
    @GetMapping("/users")
    public Result<PageResult<UserDTO>> getUsers(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "用户状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "搜索关键字") @RequestParam(required = false) String keyword) {
        
        checkAdminPermission();
        
        Pageable pageable = PageRequest.of(page - 1, size, Sort.by("createTime").descending());
        Page<User> userPage;
        
        // 使用预加载roles的查询方法，避免懒加载异常
        if (keyword != null && !keyword.trim().isEmpty()) {
            userPage = userRepository.searchUsersWithRoles(keyword.trim(), pageable);
            // 如果指定了状态，则过滤结果
            if (status != null) {
                List<User> filteredUsers = userPage.getContent().stream()
                        .filter(user -> user.getStatus().equals(status))
                        .collect(Collectors.toList());
                long filteredTotal = userRepository.searchUsersWithRoles(keyword.trim(), Pageable.unpaged())
                        .getContent().stream()
                        .filter(user -> user.getStatus().equals(status))
                        .count();
                userPage = new PageImpl<>(filteredUsers, pageable, filteredTotal);
            }
        } else if (status != null) {
            userPage = userRepository.findByStatusWithRoles(status, pageable);
        } else {
            userPage = userRepository.findAllWithRoles(pageable);
        }
        
        // 使用简化的转换方法，现在可以安全访问roles了
        List<UserDTO> userDTOs = userPage.getContent().stream()
                .map(user -> userService.convertToSimpleUserDTO(user))
                .collect(Collectors.toList());
        
        return Result.success("获取成功", PageResult.of(userDTOs, userPage.getTotalElements(), page, size));
    }
    
    /**
     * 启用/禁用用户
     */
    @Operation(summary = "用户状态管理", description = "启用或禁用用户账号")
    @PutMapping("/users/{userId}/status")
    @Transactional
    public Result<Void> updateUserStatus(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "状态") @RequestParam Integer status) {
        
        checkAdminPermission();
        
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));
        
        user.setStatus(status);
        userRepository.save(user);
        
        return Result.success(status == 1 ? "用户已启用" : "用户已禁用");
    }
    
    /**
     * 获取帖子列表（管理员视图）
     */
    @Operation(summary = "帖子管理", description = "获取所有帖子列表")
    @GetMapping("/posts")
    public Result<PageResult<PostDTO>> getPosts(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "帖子状态") @RequestParam(required = false) Integer status) {
        
        checkAdminPermission();
        
        Pageable pageable = PageRequest.of(page - 1, size, Sort.by("createTime").descending());
        Page<Post> postPage;
        
        if (status != null) {
            postPage = postRepository.findByStatus(status, pageable);
        } else {
            postPage = postRepository.findAll(pageable);
        }
        
        List<PostDTO> postDTOs = postPage.getContent().stream()
                .map(post -> postService.getPostById(post.getId()))
                .collect(Collectors.toList());
        
        return Result.success("获取成功", PageResult.of(postDTOs, postPage.getTotalElements(), page, size));
    }
    
    /**
     * 更新帖子状态
     */
    @Operation(summary = "帖子状态管理", description = "更新帖子状态（发布、删除等）")
    @PutMapping("/posts/{postId}/status")
    @Transactional
    public Result<Void> updatePostStatus(
            @Parameter(description = "帖子ID") @PathVariable Long postId,
            @Parameter(description = "状态") @RequestParam Integer status) {
        
        checkAdminPermission();
        
        Post post = postRepository.findById(postId)
                .orElseThrow(() -> new ResourceNotFoundException("帖子不存在"));
        
        post.setStatus(status);
        postRepository.save(post);
        
        return Result.success("帖子状态更新成功");
    }
    
    /**
     * 设置帖子置顶
     */
    @Operation(summary = "帖子置顶", description = "设置或取消帖子置顶")
    @PutMapping("/posts/{postId}/top")
    @Transactional
    public Result<Void> updatePostTop(
            @Parameter(description = "帖子ID") @PathVariable Long postId,
            @Parameter(description = "是否置顶") @RequestParam Boolean isTop) {
        
        checkAdminPermission();
        
        Post post = postRepository.findById(postId)
                .orElseThrow(() -> new ResourceNotFoundException("帖子不存在"));
        
        post.setIsTop(isTop ? 1 : 0);
        postRepository.save(post);
        
        return Result.success(isTop ? "帖子已置顶" : "已取消置顶");
    }
    
    /**
     * 获取评论列表（管理员视图）
     */
    @Operation(summary = "评论管理", description = "获取所有评论列表")
    @GetMapping("/comments")
    public Result<PageResult<Map<String, Object>>> getComments(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "评论状态") @RequestParam(required = false) Integer status) {
        
        checkAdminPermission();
        
        Pageable pageable = PageRequest.of(page - 1, size, Sort.by("createTime").descending());
        Page<Comment> commentPage;
        
        if (status != null) {
            commentPage = commentRepository.findByStatus(status, pageable);
        } else {
            commentPage = commentRepository.findAll(pageable);
        }
        
        List<Map<String, Object>> commentData = commentPage.getContent().stream()
                .map(this::convertCommentToMap)
                .collect(Collectors.toList());
        
        return Result.success("获取成功", PageResult.of(commentData, commentPage.getTotalElements(), page, size));
    }
    
    /**
     * 删除评论
     */
    @Operation(summary = "删除评论", description = "管理员删除评论")
    @DeleteMapping("/comments/{commentId}")
    @Transactional
    public Result<Void> deleteComment(@Parameter(description = "评论ID") @PathVariable Long commentId) {
        
        checkAdminPermission();
        
        Comment comment = commentRepository.findById(commentId)
                .orElseThrow(() -> new ResourceNotFoundException("评论不存在"));
        
        comment.setStatus(0); // 软删除
        commentRepository.save(comment);
        
        return Result.success("评论删除成功");
    }
    
    /**
     * 获取分类管理
     */
    @Operation(summary = "分类管理", description = "获取所有分类")
    @GetMapping("/categories")
    public Result<List<Map<String, Object>>> getCategories() {
        
        checkAdminPermission();
        
        List<Category> categories = categoryRepository.findAll();
        List<Map<String, Object>> categoryData = categories.stream()
                .map(this::convertCategoryToMap)
                .collect(Collectors.toList());
        
        return Result.success("获取成功", categoryData);
    }
    
    /**
     * 创建分类
     */
    @Operation(summary = "创建分类", description = "创建新的分类")
    @PostMapping("/categories")
    @Transactional
    public Result<Map<String, Object>> createCategory(
            @Parameter(description = "分类名称") @RequestParam String name,
            @Parameter(description = "分类描述") @RequestParam(required = false) String description,
            @Parameter(description = "父分类ID") @RequestParam(defaultValue = "0") Long parentId,
            @Parameter(description = "排序") @RequestParam(defaultValue = "0") Integer sortOrder) {
        
        checkAdminPermission();
        
        Category category = new Category();
        category.setName(name);
        category.setDescription(description);
        category.setParentId(parentId);
        category.setSortOrder(sortOrder);
        category.setStatus(1);
        
        category = categoryRepository.save(category);
        
        return Result.success("分类创建成功", convertCategoryToMap(category));
    }
    
    /**
     * 更新分类
     */
    @Operation(summary = "更新分类", description = "更新分类信息")
    @PutMapping("/categories/{categoryId}")
    @Transactional
    public Result<Map<String, Object>> updateCategory(
            @Parameter(description = "分类ID") @PathVariable Long categoryId,
            @Parameter(description = "分类名称") @RequestParam(required = false) String name,
            @Parameter(description = "分类描述") @RequestParam(required = false) String description,
            @Parameter(description = "排序") @RequestParam(required = false) Integer sortOrder,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        
        checkAdminPermission();
        
        Category category = categoryRepository.findById(categoryId)
                .orElseThrow(() -> new ResourceNotFoundException("分类不存在"));
        
        if (name != null) category.setName(name);
        if (description != null) category.setDescription(description);
        if (sortOrder != null) category.setSortOrder(sortOrder);
        if (status != null) category.setStatus(status);
        
        category = categoryRepository.save(category);
        
        return Result.success("分类更新成功", convertCategoryToMap(category));
    }
    
    /**
     * 删除分类
     */
    @Operation(summary = "删除分类", description = "删除分类")
    @DeleteMapping("/categories/{categoryId}")
    @Transactional
    public Result<Void> deleteCategory(@Parameter(description = "分类ID") @PathVariable Long categoryId) {
        
        checkAdminPermission();
        
        Category category = categoryRepository.findById(categoryId)
                .orElseThrow(() -> new ResourceNotFoundException("分类不存在"));
        
        // 检查是否有帖子使用此分类
        long postCount = postRepository.countByCategoryId(categoryId);
        if (postCount > 0) {
            throw new BusinessException("该分类下还有帖子，无法删除");
        }
        
        categoryRepository.delete(category);
        
        return Result.success("分类删除成功");
    }
    
    /**
     * 设置用户为管理员
     */
    @Operation(summary = "设置管理员", description = "为用户添加管理员角色")
    @PostMapping("/users/{userId}/admin")
    @Transactional
    public Result<Void> setUserAsAdmin(@Parameter(description = "用户ID") @PathVariable Long userId) {
        
        checkSystemAdminPermission(); // 只有系统管理员可以设置管理员
        
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));
        
        // 查找管理员角色
        Role adminRole = roleRepository.findByRoleName("ADMIN")
                .orElseThrow(() -> new BusinessException("管理员角色不存在"));
        
        // 检查用户是否已经是管理员
        boolean isAlreadyAdmin = user.getRoles().stream()
                .anyMatch(role -> "ADMIN".equals(role.getRoleName()) || "SYSTEM_ADMIN".equals(role.getRoleName()));
        
        if (isAlreadyAdmin) {
            throw new BusinessException("用户已经是管理员");
        }
        
        // 添加管理员角色
        user.getRoles().add(adminRole);
        userRepository.save(user);
        
        return Result.success("用户已设置为管理员");
    }
    
    /**
     * 取消用户管理员身份
     */
    @Operation(summary = "取消管理员", description = "移除用户的管理员角色")
    @DeleteMapping("/users/{userId}/admin")
    @Transactional
    public Result<Void> removeUserAdmin(@Parameter(description = "用户ID") @PathVariable Long userId) {
        
        checkSystemAdminPermission(); // 只有系统管理员可以取消管理员身份
        
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));
        
        // 防止取消自己的管理员身份
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (userId.equals(currentUserId)) {
            throw new BusinessException("不能取消自己的管理员身份");
        }
        
        // 防止取消系统管理员身份
        boolean isSystemAdmin = user.getRoles().stream()
                .anyMatch(role -> "SYSTEM_ADMIN".equals(role.getRoleName()));
        if (isSystemAdmin) {
            throw new BusinessException("不能取消系统管理员身份");
        }
        
        // 移除管理员角色
        user.getRoles().removeIf(role -> "ADMIN".equals(role.getRoleName()));
        userRepository.save(user);
        
        return Result.success("已取消用户管理员身份");
    }

    /**
     * 删除帖子
     */
    @Operation(summary = "删除帖子", description = "管理员删除帖子")
    @DeleteMapping("/posts/{postId}")
    @Transactional
    public Result<Void> deletePost(@Parameter(description = "帖子ID") @PathVariable Long postId) {
        
        checkAdminPermission();
        
        Post post = postRepository.findById(postId)
                .orElseThrow(() -> new ResourceNotFoundException("帖子不存在"));
        
        post.setStatus(0); // 软删除
        postRepository.save(post);
        
        return Result.success("帖子删除成功");
    }
    
    /**
     * 恢复帖子
     */
    @Operation(summary = "恢复帖子", description = "管理员恢复已删除的帖子")
    @PutMapping("/posts/{postId}/restore")
    @Transactional
    public Result<Void> restorePost(@Parameter(description = "帖子ID") @PathVariable Long postId) {
        
        checkAdminPermission();
        
        Post post = postRepository.findById(postId)
                .orElseThrow(() -> new ResourceNotFoundException("帖子不存在"));
        
        post.setStatus(1); // 恢复状态
        postRepository.save(post);
        
        return Result.success("帖子恢复成功");
    }

    /**
     * 搜索用户
     */
    @Operation(summary = "搜索用户", description = "根据关键字搜索用户")
    @GetMapping("/users/search")
    public Result<PageResult<UserDTO>> searchUsers(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "搜索关键字") @RequestParam String keyword,
            @Parameter(description = "用户状态") @RequestParam(required = false) Integer status) {
        
        checkAdminPermission();
        
        Pageable pageable = PageRequest.of(page - 1, size, Sort.by("createTime").descending());
        Page<User> userPage = userRepository.searchUsersWithRoles(keyword, pageable);
        
        // 如果指定了状态，则过滤结果，使用简化的转换方法
        List<UserDTO> userDTOs = userPage.getContent().stream()
                .filter(user -> status == null || user.getStatus().equals(status))
                .map(user -> userService.convertToSimpleUserDTO(user))
                .collect(Collectors.toList());
        
        return Result.success("搜索成功", PageResult.of(userDTOs, userPage.getTotalElements(), page, size));
    }

    /**
     * 搜索帖子
     */
    @Operation(summary = "搜索帖子", description = "根据关键字搜索帖子")
    @GetMapping("/posts/search")
    public Result<PageResult<PostDTO>> searchPosts(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "搜索关键字") @RequestParam String keyword,
            @Parameter(description = "分类ID") @RequestParam(required = false) Long categoryId,
            @Parameter(description = "帖子状态") @RequestParam(required = false) Integer status) {
        
        checkAdminPermission();
        
        Pageable pageable = PageRequest.of(page - 1, size, Sort.by("createTime").descending());
        Page<Post> postPage;
        
        // 根据参数选择合适的搜索方法
        if (categoryId != null) {
            postPage = postRepository.searchPostsInCategory(keyword, categoryId, pageable);
        } else {
            postPage = postRepository.searchPosts(keyword, pageable);
        }
        
        // 如果指定了状态，则过滤结果
        List<PostDTO> postDTOs = postPage.getContent().stream()
                .filter(post -> status == null || post.getStatus().equals(status))
                .map(post -> postService.getPostById(post.getId()))
                .collect(Collectors.toList());
        
        return Result.success("搜索成功", PageResult.of(postDTOs, postPage.getTotalElements(), page, size));
    }
    
    /**
     * 检查管理员权限
     */
    private void checkAdminPermission() {
        if (!SecurityUtils.isAdmin()) {
            throw new ForbiddenException("需要管理员权限");
        }
    }
    
    /**
     * 检查系统管理员权限（只有SYSTEM_ADMIN才能管理其他管理员）
     */
    private void checkSystemAdminPermission() {
        if (!SecurityUtils.isSystemAdmin()) {
            throw new ForbiddenException("需要系统管理员权限");
        }
    }
    
    /**
     * 转换评论为Map
     */
    private Map<String, Object> convertCommentToMap(Comment comment) {
        Map<String, Object> data = new HashMap<>();
        data.put("id", comment.getId());
        data.put("content", comment.getContent());
        data.put("postId", comment.getPostId());
        data.put("userId", comment.getUserId());
        data.put("likeCount", comment.getLikeCount());
        data.put("status", comment.getStatus());
        data.put("createTime", comment.getCreateTime());
        
        // 用户信息
        userRepository.findById(comment.getUserId()).ifPresent(user -> {
            data.put("username", user.getUsername());
        });
        
        // 帖子信息
        postRepository.findById(comment.getPostId()).ifPresent(post -> {
            data.put("postTitle", post.getTitle());
        });
        
        return data;
    }
    
    /**
     * 转换分类为Map
     */
    private Map<String, Object> convertCategoryToMap(Category category) {
        Map<String, Object> data = new HashMap<>();
        data.put("id", category.getId());
        data.put("name", category.getName());
        data.put("description", category.getDescription());
        data.put("parentId", category.getParentId());
        data.put("sortOrder", category.getSortOrder());
        data.put("status", category.getStatus());
        data.put("createTime", category.getCreateTime());
        
        // 统计该分类下的帖子数量
        long postCount = postRepository.countByCategoryId(category.getId());
        data.put("postCount", postCount);
        
        return data;
    }
    
    /**
     * 系统概览数据
     */
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class SystemOverview {
        private Long totalUsers;
        private Long activeUsers;
        private Long totalPosts;
        private Long publishedPosts;
        private Long totalComments;
        private Long totalWhispers;
        private Long totalFiles;
        private Long todayPosts;
        private Long todayComments;
        private Long todayWhispers;
        private Long todayFiles;
    }
} 